package com.gzhryc.servlet.resources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpHeaders;
import org.apache.velocity.VelocityContext;

import com.gzhryc.servlet.Resource;
import com.gzhryc.servlet.VelocityService;

public class VelocityResource extends Resource {

	private String templateName;
	private VelocityContext velocityContext;

	public VelocityResource(String mediaType,String templateName) {
		super(mediaType);
		this.templateName = templateName;
	}
	
	public VelocityResource(String templateName) {
		super("text/html");
		this.templateName = templateName;
	}
	
	public void setVelocityContext(VelocityContext velocityContext){
		this.velocityContext = velocityContext;
	}
	
	public VelocityContext getVelocityContext(){
		if(this.velocityContext == null){
			this.velocityContext = new VelocityContext();
		}
		return this.velocityContext;
	}
	
	public String getTemplateName(){
		return this.templateName;
	}
	
	public void setTemplateName(String templateName){
		this.templateName = templateName;
	}
	
	@Override
	public void export(HttpServletRequest request,HttpServletResponse response) throws Exception {
		VelocityService velocityService = VelocityService.self();
		if(velocityService != null){
			response.addHeader(HttpHeaders.CONTENT_TYPE,this.getMediaType());
			response.setCharacterEncoding(this.getCharset().name());
			velocityService.export(request,response,templateName,getVelocityContext());
		}else{
			throw new Exception("未找到页面渲染引擎");
		}
	}
}
